package com.vogue.supplymall.common.domain.tool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Locale;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Component;

/**
 * 获取国际化信息的工具类
 * 
 * @author 崔岳
 *
 */
@Component("messageSourceUtils") 
public class MessageSourceUtils {
 
	public static final Logger LOGGER_MESSAGESOURCEUTILS = LoggerFactory.getLogger(MessageSourceUtils.class);
	
	private static ResourceBundleMessageSource messageSource;
	/**
	 * 国际化语言
	 */
	@Value("${local.language}")
	private String language = "zh";
	/**
	 * 国际化国家
	 */
	@Value("${local.country}")
	private String country = "CN";
	
	public MessageSourceUtils() {
		if(messageSource == null) {
			messageSource = new ResourceBundleMessageSource();
			messageSource.setDefaultEncoding("UTF-8");
		}
		messageSource.setBasenames("i18n/messages");
	}
	
	public MessageSourceUtils(String...basenames) {
		if(messageSource == null) {			
			messageSource = new ResourceBundleMessageSource();
			messageSource.setDefaultEncoding("UTF-8");
		}
		messageSource.setBasenames("i18n/messages");
		messageSource.addBasenames(basenames);
	}
	
	
	public MessageSourceUtils(String language, String country) {
		this.language = language;
		this.country = country;
	}

	private static Locale local = null;

	private Locale getLocale() {
		if (local == null) {
			if(language == null) {
				language = "zh";
			}
			if(country == null) {
				if("zh".equals(language)) {
					country = "CN";
				}else {
					language = "zh";
					country = "CN";
				}				
			}
			local = new Locale(language, country);
		}
		return local;
	}

	public String getMessage(String code, Object[] args) {
		try {
			return messageSource.getMessage(code, args, getLocale());
		} catch (NoSuchMessageException nme) {
		    LOGGER_MESSAGESOURCEUTILS.error("NoSuchMessage : "+code);
			return code;
		}
	}
}
